<template>
	<view class="address-list">
		<van-address-list
		  v-model="chosenAddressId"
		  :list="list"
		  default-tag-text="默认"
		  :add-button-text="text"
		  @add="onAdd"
		  @edit="onEdit"
		  @click-item="clickAddress"
		/>

	</view>
</template>

<script>
	import { ref } from 'vue';
	const UserDB = uniCloud.importObject('user');
	import Storage from '@/utils/storage.js'
	
	export default {
	  setup(o) {
		let btnName = "选中地址"
		if(o.page == 'user'){
			btnName ='添加地址';
		}
		const page = o.page;
		const text = ref(btnName);

	    const onAdd = () => {
			if(page == 'user'){
				// 跳转到添加页面
				uni.navigateTo({
					url:"/pages/user/address/add"
				})
			}else{
				// 设置默认地址  返回页面
				uni.navigateBack()
			}
			
		};
	    const onEdit = (item, index) => {
			uni.navigateTo({
				url:"/pages/user/address/add?info="+JSON.stringify(item)
			})
		};
	    return {
		  text,
	      onAdd,
		  page,
	      onEdit,
	      chosenAddressId:ref(''),
	    };
	  },
	  data(){
		  return {
			  list:[]
		  }
	  },
	  onLoad(){
		  let userInfo = Storage.UserInfo
		  this.getAddress(userInfo._id)
	  },
	  methods:{
		  getAddress(userId){
				UserDB.addressList(userId).then(res=>{
					this.list = res.data
					this.chosenAddressId = res.defaultId
					console.log(this.chosenAddressId);
				})
		  },
		  clickAddress(e){
			  this.chosenAddressId = e._id;
			  this.$store.commit("addAddress",e)
			  UserDB.setAddressDefault(e._id,Storage.UserInfo._id)
		  }
	  }
	};

</script>

<style>
</style>